<template>
  <div class="flex-container">
    <el-select-v2
        v-model="param.fromCost"
        :options="options"
        placeholder="租金下限"
        style="width: 240px; margin-right: 20px;"
        @change="getRooms"
    />

    <el-select-v2
        v-model="param.toCost"
        :options="filteredCostOptions"
        placeholder="租金上限"
        :disabled="isSelectDisabled"
        style="width: 240px; margin-right: 20px;"
        @change="getRooms"
    />
    <el-input v-model="param.address" placeholder="请输入地址" style="width: 240px ;margin-right:20px" @input="getRooms"/>
    <el-input v-model="param.type" placeholder="请输入户型" style="width: 240px ;margin-right:20px" @input="getRooms"/>


    <el-button type="primary" @click="openDialog">新增</el-button>

    <el-dialog v-model="dialogVisible" title="Dialog Title">
      <!-- 使用 el-form 显示描述列表的数据 -->
      <el-form :model="addForm" label-position="left" label-width="120px">
        <el-form-item label="地址">
          <el-input v-model="addForm.address" />
        </el-form-item><el-form-item label="房间号">
        <el-input v-model="addForm.roomNumber" />
      </el-form-item><el-form-item label="户型">
        <el-input v-model="addForm.type" />
      </el-form-item>
        <el-form-item label="租金">
          <el-input v-model="addForm.cost" />
        </el-form-item><el-form-item label="押金">
        <el-input v-model="addForm.cashPledge" />
      </el-form-item><el-form-item label="描述">
        <el-input v-model="addForm.description" />
      </el-form-item><el-form-item label="初始电度数">
        <el-input v-model="addForm.electricity" />
      </el-form-item><el-form-item label="初始水吨数">
        <el-input v-model="addForm.water" />
      </el-form-item>
        <el-form-item label="图片">
          <el-upload
              class="avatar-uploader"
              :action="`${OpenAPI.BASE}/common/upload`"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <!-- 其他描述列表的项 ... -->
        <el-button type="primary" @click="addRoom" style="margin-top: 30px">确认新增</el-button>
      </el-form>
    </el-dialog>

  </div>
  <div  v-loading="loading" >
    <el-row :gutter="20">
      <el-col v-for="room in rooms" :key="room.id" :span="8">
        <el-card :body-style="{ padding: '0px' }" class="room-card">

          <img :src="`${OpenAPI.BASE}/common/download?name=${room.image}`" class="image" @click="getRoom(room.id),dAddress=room.address,rentParam.room=room.id"/>

          <div style="padding: 14px; display: flex; flex-direction: row;">
            <span style="margin-right:10px">{{ room.address }}</span>
            <span style="margin-right:10px">
              <span>{{ room.cost }}</span>
            </span>
            <span style="margin-right:10px">{{ room.type }}</span>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-empty v-if="rooms.length === 0" description="暂无数据"></el-empty>

    <el-pagination
        v-if="rooms.length"
        class="pageList"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="param.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        v-model:current-page="page"
        @current-change="handleCurrentChange"
    ></el-pagination>


    <el-drawer v-model="drawer" title="修改房间信息" :with-header="false">
      <div class="product-detail">
        <el-card class="product-card">
          <el-divider></el-divider>
          <!-- 使用 el-form 显示描述列表的数据 -->
          <el-form :model="updateForm" label-position="left" label-width="120px">
            <el-form-item label="租金">
              <el-input v-model="updateForm.cost" />
            </el-form-item>
            <el-form-item label="押金">
              <el-input v-model="updateForm.cashPledge" />
            </el-form-item>
            <el-form-item label="描述">
              <el-input v-model="updateForm.description" />
            </el-form-item>
            <el-form-item label="房间号">
              <el-input v-model="updateForm.roomNumber" />
            </el-form-item>
            <!-- 其他表单项 ... -->
          </el-form>

          <!-- 确认修改按钮 -->
          <el-button type="primary" @click="submitUpdate" style="margin-top: 30px">确认修改</el-button>
        </el-card>
      </div>
      <br>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import {ref, onMounted, reactive, watch, computed} from 'vue';
import {ElMessage, ElMessageBox, MessageBox, UploadProps} from 'element-plus';
import {
  OpenAPI,
  RentDetail_,
  RentDetaioDto, RoomManage_,
  RoomManageControllerService,
  RoomRequestParam,
  User_
} from '../../generated';
import {Plus} from "@element-plus/icons-vue";




const rooms = ref([]);
const total = ref(0);
const page = ref(1);
let drawer = ref(false)
let dAddress=ref();
const room=ref();
const num=ref(0);
const param = reactive({
  address: "",
  current: page.value,
  fromCost: "",
  pageSize: 10, // 默认每页显示10条
  toCost: "",
  type: ""
} as unknown as RoomRequestParam);


const imageUrl=ref();
const handleAvatarSuccess = (response) => {
  console.log(response)
  addForm.value.image= `${response.message}`
  imageUrl.value = `${OpenAPI.BASE}/common/download?name=${response.message}`
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}



const costOptions = ref([
  { value: '', label: '租金上限不限' },
  { value: '1000', label: '1000' },
  { value: '2000', label: '2000' },
  { value: '3000', label: '3000' },
]);

// 计算属性，用于判断是否禁用 el-select-v2
const isSelectDisabled = computed(() => {
  return param.fromCost === '';
});

// 计算属性，过滤掉比 param.fromCost 小的选项
const filteredCostOptions = computed(() => {
  return costOptions.value.filter(option => option.value === '' || parseInt(option.value) > parseInt(param.fromCost));
});

// 监听 param.fromCost 的变化
watch(() => param.fromCost, (newVal) => {
  // 可以在这里进行其他操作
});
const rentParam=reactive({
  rentFrom:'',
  rentTo:'',
  room:'',
} as unknown as RentDetaioDto);


const submitUpdate=async () => {
  try {
    const response = await RoomManageControllerService.updateManageUsingPost(updateForm);
    if (response.code === 200) {
      ElMessage.success("修改成功");
    } else {
      ElMessage.error('修改失败:', response.message);
    }
  } catch (error) {
    console.error('Error fetching rooms:', error);
  }
};



let loading=false;

const options = ref([
  { value: '', label: '租金下限不限' },
  { value: '0', label: '0' },
  { value: '1000', label: '1000' },
  { value: '2000', label: '2000' },
  { value: '3000', label: '3000' },
])

const getToRent = () => {
  // 检查 rentParam.rentFrom 和 num 是否存在
  if (rentParam.rentFrom && num) {
    // 复制 rentFrom 的日期
    const rentTo = new Date(rentParam.rentFrom);

    // 将日期增加 num 个月
    rentTo.setMonth(rentTo.getMonth() + num.value);

    // 更新 rentParam.rentTo
    rentParam.rentTo = rentTo.toLocaleDateString('en-CA'); // 使用合适的语言标识符

    // 格式化 rentFrom
    rentParam.rentFrom = new Date(rentParam.rentFrom).toLocaleDateString('en-CA');
  } else {
    console.error("rentFrom and num must be defined");
  }
}

const getRooms = async () => {
  try {
    const response = await RoomManageControllerService.listPageUsingPost1(param);
    if (response.code === 200) {
      rooms.value = response.result.list;
      total.value = response.result.total;
      loading=false;
    } else {
      console.error('Failed to fetch rooms:', response.message);
    }
  } catch (error) {
    console.error('Error fetching rooms:', error);
  }
};
const getRoom = async (id) => {
  drawer.value = true;
  try {
    const response = await RoomManageControllerService.getDetailUsingGet(id);
    if (response.code === 200) {
      const roomData = response.result;
      updateForm.id=roomData.id;
      updateForm.cost = roomData.cost;
      updateForm.cashPledge = roomData.cashPledge || '';
      updateForm.description = roomData.description || '';
      updateForm.roomNumber = roomData.roomNumber || '';
      updateForm.image=roomData.image;
    } else {
      console.error('Failed to fetch room:', response.message);
    }
  } catch (error) {
    console.error('Error fetching room:', error);
  }
};
// const getRoom = async (id) => {
//   drawer.value = true;
//   try {
//     const response = await RoomManageControllerService.getDetailUsingGet(id);
//     if (response.code === 200) {
//       room.value = response.result;
//       updateForm = ({
//         cost: room.value.cost ,
//         cashPledge: room.value?.cashPledge ,
//         description: room.value?.description,
//         image: room.value.image,
//         roomNumber: room.value.roomNumber
//       })
//       console.log(updateForm)
//     } else {
//       console.error('Failed to fetch room:', response.message);
//     }
//   } catch (error) {
//     console.error('Error fetching room:', error);
//   }
// };
const handleSelectionChange = (selection: any) => {
  console.log('Selected Rooms:', selection);
};

const handleSizeChange = (pageSize: number | undefined) => {
  param.pageSize = pageSize;
  getRooms();
};

const handleCurrentChange = (currentPage: number | undefined) => {
  param.current = currentPage;
  getRooms();
};

onMounted(() => {
  getRooms();
});


let updateForm = reactive({
  id:'',
  cost: '',
  cashPledge: '',
  description: '',
  image: '',
  roomNumber: ''
} as unknown as RoomManage_);


let addForm=ref({
  cost:'',
  cashPledge:'',
  description:'',
  image:'',
  address:'',
  electricity:'',
  water:'',
  type:'',
  roomNumber:''
})


const addRoom =async () => {
  try {
    const response = await RoomManageControllerService.addManageUsingPost(addForm.value);
    if (response.code === 200) {
      loading=false;
      dialogVisible.value=false;
      imageUrl.value='';
      getRooms();
    } else {
      // console.error('Failed to fetch rooms:', response.message);
      ElMessage.error(response.message);
    }
  } catch (error) {
    console.error('Error fetching rooms:', error);
  }
};

const dialogVisible = ref(false);
const openDialog = () => {
  // 打开弹出框时，将描述列表的数据赋值给 el-form 的数据
  addForm.value= {
    cost:'',
    cashPledge:'',
    description:'',
    image:'',
    address:'',
    electricity:'',
    water:'',
    type:'',
    roomNumber:''
    // ... 获取其他属性的数据 ...
  };
  dialogVisible.value = true;
};
</script>

<style scoped>
.pageList {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 8px 8px 0 0;
}

.room-card {
  border: 1px solid #ddd;
  border-radius: 8px;
  transition: border 0.2s ease-in-out 0.2s, transform 0.4s ease-in-out 0.1s;
  margin-bottom: 20px;
}

.room-card:hover {
  border: 1px solid #409EFF;
  transform: translateY(-5px);
}

.room-info {
  display: flex;
  flex-direction: column;
  padding: 14px;
  text-align: center;
}

.room-info span {
  margin: 8px 0;
}

.flex-container {
  display: flex;
  margin-bottom: 20px;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
